package dyy.zc.campuspay.utils;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.util.Log;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;

import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;
import dyy.zc.campuspay.application.MyApplication;
import dyy.zc.campuspay.bean.Account;
import dyy.zc.campuspay.bean.OrderInfo;
import dyy.zc.campuspay.constant.Constants;
import dyy.zc.campuspay.ui.activity.LoginActivity;
import dyy.zc.campuspay.ui.activity.MainActivity;
import dyy.zc.campuspay.ui.activity.RegisterActivity;
import dyy.zc.campuspay.ui.activity.ZhifuPasswordActivity;
import dyy.zc.campuspay.ui.activity.ZhuanZhangActivity;
import dyy.zc.campuspay.ui.fragment.MineFragment;
import dyy.zc.campuspay.ui.fragment.QueryFragment;

/**
 * Created by chuan on 2017/3/10.
 */

public class BmobUtils {
    public static boolean loginSuccess = false;
    public static boolean query = false;
    public static int queryCount = 0;
    private boolean registerSuccess = true;
    private Context context;
    public static List<OrderInfo> list_order = new ArrayList<>();
    public BmobUtils(Context context){
        this.context = context;
    }

    /**
     * 获取用户最新信息
     * @param account
     * @param resultCode
     * @param handler
     */
    public void getUserInfo(final String account, final  int resultCode, final Handler handler){
        BmobQuery<Account> query = new BmobQuery<>();
        query.findObjects(new FindListener<Account>() {
            @Override
            public void done(List<Account> list, BmobException e) {
                if (e==null){
                    Log.e("getUserInfo", "ok");
                    for (Account account1:list){
                        if (account1.getAccount().equals(account)){
                            ((MainActivity)context).mineFragment.account = account1;
                            break;
                        }
                    }
                    handler.sendEmptyMessage(resultCode);
                }else {
                    Log.e("getUserInfo", e.getMessage());
                }
            }
        });
    }

    /**
     * 增加用户
     * @param account
     */
    public void addUserInfo(final Account account) {
        account.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null){
                    Log.e("updateInfoFailed", "ok");
                    ((RegisterActivity) context).account.setId(s);
                    ((RegisterActivity) context).handler.sendEmptyMessage(Constants.ResultCode.SUCCESS);
                }else {
                    Log.e("Bmob-updateInfoFailed", e.getMessage());
                }
            }
        });
    }

    public void getBackYourAccount(final String phone, final String userPassword){
        final BmobQuery<Account> query = new BmobQuery<>();
        query.findObjects(new FindListener<Account>() {
            @Override
            public void done(List<Account> list, BmobException e) {
                if (e == null){
                    Log.e("getBackYourAccount", "ok");
                    for (Account a :
                            list) {
                        if (a.getAccount().equals(phone)){
                            Account account = new Account();
                            account.setId(a.getId());
                            account.setAccount(a.getAccount());
                            account.setNikeName(a.getNikeName());
                            account.setHead(a.getHead());
                            account.setRealName(a.getRealName());
                            account.setPassword(userPassword);
                            findPassword(account);
                            break;
                        }
                    }
                }else {
                    Log.e("getBackYourAccount", e.getMessage());
                }
            }
        });
    }

    /**
     * 注册新用户验证
     * @param userPhone 账号
     */
    public void registerChecked(final String userPhone) {
        BmobQuery<Account> query = new BmobQuery<>();
        query.findObjects(new FindListener<Account>() {
            @Override
            public void done(List<Account> list, BmobException e) {
                for (Account a :
                        list) {
                    if (a.getAccount().equals(userPhone)) {
                        registerSuccess = false;
                        break;
                    }
                }
                if (!registerSuccess) {
                    ((RegisterActivity) context).handler.sendEmptyMessage(Constants.ResultCode.REGISTER_FAILED);
                } else {
                    ((RegisterActivity) context).handler.sendEmptyMessage(Constants.ResultCode.REGISTER_SUCCESS);
                }
            }
        });
    }
    /**
     * 登录查询是否账号密码输入错误
     */
    public void queryAccount(final Account account) {
        BmobQuery<Account> bmobQuery = new BmobQuery<>();
        bmobQuery.findObjects(new FindListener<Account>() {
            @Override
            public void done(List<Account> list, BmobException e) {
                if (e == null) {
                    Log.e("queryAccount", "ok");
                    for (Account a :
                            list) {
                        if (a.getAccount().equals(account.getAccount()) && a.getPassword().equals(account.getPassword())) {
                            loginSuccess = true;
                            Account userInfo = new Account();
                            userInfo.setAccount(a.getAccount());
                            userInfo.setPassword(a.getPassword());
                            userInfo.setId(a.getObjectId());
                            userInfo.setRealName(a.getRealName());
                            userInfo.setNikeName(a.getNikeName());
                            userInfo.setHead(a.getHead());
                            userInfo.setRemain(a.getRemain());
                            MyApplication.getInstance().saveUserInfo(userInfo);
                            //((LoginActivity) context).account.setId(a.getObjectId());
                            break;
                        }
                    }
                } else {
                    e.printStackTrace();
                    Log.e("queryAccount", "Failed");
                }
                ((LoginActivity) context).handler.sendEmptyMessage(Constants.ResultCode.RESULT_SUCCESS);
            }
        });
    }

    /**
     * 更新用户密码
     *
     * @param account
     */
    public void findPassword(Account account) {
        account.update(account.getId(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Log.e("updateAccountInfo", "ok");
                    ((RegisterActivity) context).handler.sendEmptyMessage(Constants.ResultCode.SUCCESS);
                } else {
                    e.printStackTrace();
                    Log.e("updateAccountInfo", e.getMessage());
                }
            }
        });
    }
    /**
     * 更新用户信息
     *
     * @param account
     */
    public void updateAccountInfo(Account account) {
        account.update(account.getId(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Log.e("updateAccountInfo", "ok");
                } else {
                    e.printStackTrace();
                    Log.e("updateAccountInfo", e.getMessage());
                }
            }
        });
    }
    /**
     * 更新用户信息--设置支付密码
     *
     * @param account
     */
    public void updateAccount(Account account) {
        account.update(account.getId(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Log.e("updateAccountInfo", "ok");
                    ((ZhifuPasswordActivity)context).handler.sendEmptyMessage(50);
                } else {
                    e.printStackTrace();
                    Log.e("updateAccountInfo", e.getMessage());
                }
            }
        });
    }
    /**
     * 上传图片文件--用户头像
     *
     * @param bmobFile
     * @param imageFile
     */
    public void upLoadFile(final BmobFile bmobFile, File imageFile) {
        final Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getPath());
        MineFragment.civ_head.setImageBitmap(bitmap);
        bmobFile.upload(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Account account = MyApplication.getInstance().readLoginUser();
                    account.setHead(bmobFile);
                    MyApplication.getInstance().saveUserInfo(account);
                    updateAccountInfo(account);
                    MineFragment.civ_head.setImageBitmap(bitmap);
                    Log.e("upLoadFile", "ok--" + bmobFile.getFileUrl());
                } else {
                    e.printStackTrace();
                    Log.e("upLoadFile", e.getMessage());
                }
            }
        });
    }

    /**
     * 查询转账的账号
     * @param id
     */
    public void queryZhuanAccount(final String id){
        BmobQuery<Account> query = new BmobQuery<>();
        query.findObjects(new FindListener<Account>() {
            @Override
            public void done(List<Account> list, BmobException e) {
                if (e == null) {
                    Log.e("queryAccount", "ok");
                    for (Account a:list){
                        if (a.getObjectId().equals(id)){
                            ((ZhuanZhangActivity)context).account = a;
                            ((ZhuanZhangActivity)context).handler.sendEmptyMessage(Constants.ResultCode.SUCCESS);
                            break;
                        }
                    }
                } else {
                    e.printStackTrace();
                    Log.e("queryAccount", e.getMessage());
                }
            }
        });
    }

    /**
     * 查询账单记录
     */
    public void queryOrderInfo(){
        list_order.clear();
        BmobQuery<OrderInfo> query = new BmobQuery<>();
        query.findObjects(new FindListener<OrderInfo>() {
            @Override
            public void done(List<OrderInfo> list, BmobException e) {
                if (e == null) {
                    Log.e("queryOrderInfo", "ok");
                    Collections.reverse(list);
                    list_order.addAll(list);
                    ((MainActivity)context).queryFragment.handler.sendEmptyMessage(Constants.ResultCode.SUCCESS);
                } else {
                    e.printStackTrace();
                    Log.e("queryOrderInfo", e.getMessage());
                }
            }
        });
    }

    /**
     * 上传订单信息--转账使用用
     * @param orderInfo
     */
    public void upLoadOrderInfo(OrderInfo orderInfo){
        orderInfo.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null) {
                    Log.e("updateInfo", "ok");
                    ((ZhuanZhangActivity)context).handler.sendEmptyMessage(Constants.ResultCode.UPLOAD_SUCCESS);
                } else {
                    e.printStackTrace();
                    Log.e("updateInfo", e.getMessage());
                }
            }
        });
    }

    /**
     * 上传订单信息--充值使用
     * @param orderInfo
     */
    public void upLoadOrder(OrderInfo orderInfo){
        orderInfo.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null) {
                    Log.e("updateInfo", "ok");

                } else {
                    e.printStackTrace();
                    Log.e("updateInfo", e.getMessage());
                }
            }
        });
    }


    /**
     * 上传图片文件--注册时默认的用户头像
     *
     * @param bmobFile
     * @param account
     */
    public void upMoRenFile(final BmobFile bmobFile, final Account account) {
        bmobFile.upload(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    account.setHead(bmobFile);
                    addUserInfo(account);
                    Log.e("upLoadFile", "ok--" + bmobFile.getFileUrl());
                } else {
                    e.printStackTrace();
                    Log.e("upLoadFile", e.getMessage());
                }
            }
        });
    }
}
